package com.mdlib.helper.api.network;

import android.util.Log;

import com.mdlib.helper.app.AppContext;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;


/**
 * Created by librabin on 16/11/15.
 */

public class CommonParamsInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
//        Request orgRequest = chain.request();
//        FormBody.Builder newBody = new FormBody.Builder();
//        newBody.add("session_id", AppContext.getInstance().getSessionId());
//        try {
//            FormBody oldBody = (FormBody) orgRequest.body();
//            for (int i = 0; i < oldBody.size(); i++)
//            {
//                newBody.add(oldBody.encodedName(i), oldBody.encodedValue(i));
//            }
//
//        } catch (Exception e) {
//
//        }
//
//        orgRequest = orgRequest.newBuilder().post(newBody.build()).build();
//
//
//
//
//        return chain.proceed(orgRequest);


        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();
        RequestBody formBody = new FormBody.Builder()
                .add("session_id", AppContext.getInstance().getSessionId())
                .build();
        String method=request.method();
        if("POST".equals(method)){
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i) + "=" + body.encodedValue(i) + ",");
                }
                sb.delete(sb.length() - 1, sb.length());
                Log.d("OkHttp: --> POST----", "| RequestParams:{"+sb.toString()+"}");
            }
        }
        String postBodyString = bodyToString(request.body());
        postBodyString += ((postBodyString.length() > 0) ? "&" : "") +  bodyToString(formBody);
        request = requestBuilder
                .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"),
                        postBodyString))
                .build();
        return chain.proceed(request);


    }


    private String bodyToString(final RequestBody request){
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if(copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        }
        catch (final IOException e) {
            return "did not work";
        }
    }

}
